//    Copyright (C) Kherty.  All rights reserved.
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Text;
using OpenLS.Chart;
using OpenLS.Core;
using OpenLS.Spreadsheet.Extensibility;

namespace OpenLS.Spreadsheet
{
    partial class Workbook
    {
        internal DateTime DoubleToDateTime(double dbl)
        {
            DateTimeOrigin origin = Properties != null ? Properties.DateTimeOrigin : DateTimeOrigin.Origin1900;
            return DateTimeConverter.DoubleToDateTime(dbl, origin); //\\missing 1904
        }

        internal double DateTimeToDouble(DateTime dt)
        {
            DateTimeOrigin origin = Properties != null ? Properties.DateTimeOrigin : DateTimeOrigin.Origin1900;
            return DateTimeConverter.DateTimeToDouble(dt, origin); //\\ missing 1904
        }

        DateTime IWorkbook.DoubleToDateTime(double dt)
        {
            return this.DoubleToDateTime(dt);
        }

        double IWorkbook.DateTimeToDouble(DateTime dt)
        {
            return this.DateTimeToDouble(dt);
        }
        T IFormatValueConverter.ChangeType<T> (object obj)
        {
            return ChangeType<T>(obj);
        }

        internal T ChangeType<T>(object value)
        {
            Type conversionType = typeof (T);
            if (value is int)
                return ChangeType<T>((double) (int) value);
            if (value.GetType() == conversionType)
                return (T) value;
            if (conversionType == typeof (DateTime))
            {
                if (value is string)
                    return ChangeType<T>(ChangeType<double>(value));
                if (value is DateTime)
                    return (T) value;
                if (value is double)
                    return (T) (object) DoubleToDateTime((double) value);
            }
            if (conversionType == typeof (double))
            {
                if (value is string)
                    return (T) (object) double.Parse((string) value, CultureInfo.InvariantCulture);
                if (value is DateTime)
                    return (T) (object) DateTimeToDouble((DateTime) value);
            }
            throw new NotImplementedException();
        }
    }
}
